package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mp.Service.IUserService;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description UserController
 * @Author cuijian
 * @Date 2024-09-18
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private  IUserService userService;

    @PostMapping
    public void saveUser(@RequestBody UserFormDTO dto){
        // 1.转换DTO为PO
        User user = BeanUtil.copyProperties(dto, User.class);
        // 2.新增
        userService.save(user);
    }
    @DeleteMapping("/{id}")
    public void removeUserById(@PathVariable("id") Long userId){
        userService.removeById(userId);
    }
    @GetMapping("/{id}")
    public UserVO queryUserById(@PathVariable("id") Long userId){
        // 1.查询用户
        User user = userService.getById(userId);
        // 2.处理vo
        return BeanUtil.copyProperties(user, UserVO.class);
    }
    @GetMapping
    public List<UserVO> queryUserByIds(@RequestParam("ids") List<Long> ids){
        // 1.查询用户
        List<User> users = userService.listByIds(ids);
        // 2.处理vo
        return BeanUtil.copyToList(users, UserVO.class);
    }
    //查询
    @GetMapping("/list")
    public List<UserVO> queryUserList(UserQuery query){
        //sql select*from user where name like ? and status = ? and balance > ? and balance <= ?
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotBlank(query.getName()), User::getUsername, query.getName());
        lqw.eq(query.getStatus() != null, User::getStatus, query.getStatus()); // 1.查询用户
        lqw.gt(query.getMinBalance() != null, User::getBalance, query.getMinBalance());
        lqw.le(query.getMaxBalance() != null, User::getBalance, query.getMaxBalance());
        List<User> users = userService.list(lqw);
        // 2.处理vo
        return BeanUtil.copyToList(users, UserVO.class);
    }


}

